<script setup lang="ts">
  import X from '@iconify-icons/tabler/x'
  import { computed } from 'vue'
  import { StrUtil } from '@xtail/core'
  import { SIcon } from '../SIcon'
  import { MaskPropsType } from './types'

  const props = withDefaults(defineProps<MaskPropsType>(), {
    close: true,
    closeHandler: () => {},
    closeOnClick: true,
    clickHandler: () => {},
    closeClass: '',
    closeStyle: '',
    body: true,
    displayDirective: 'if',
    horizontalCenter: true,
    verticalCenter: true,
    background: 'rgba(0, 0, 0, 0.7)',
    maskClass: '',
    maskStyle: ''
  })

  const value = defineModel({ default: false })

  const handleClose = () => {
    value.value = false
    props.closeHandler()
  }

  const handleClick = () => {
    if (props.closeOnClick) {
      handleClose()
    }
    props.clickHandler()
  }

  const maskStyleComputed = computed(() => {
    if (StrUtil.isStr(props.maskStyle)) {
      return `
      ${props.maskStyle};
      justify-items: ${props.horizontalCenter ? 'center' : 'initial'};
      align-items: ${props.verticalCenter ? 'center' : 'initial'};
      background: ${props.background ?? 'rgba(0, 0, 0, 0.7)'};
    `
    }
    return {
      ...props.maskStyle,
      justifyItems: props.horizontalCenter ? 'center' : 'initial',
      alignItems: props.verticalCenter ? 'center' : 'initial',
      background: props.background ?? 'rgba(0, 0, 0, 0.7)'
    }
  })
</script>

<template>
  <Teleport to="body" :disabled="!body">
    <template v-if="displayDirective === 'if'">
      <div
        class="s-mask"
        v-if="value"
        :class="maskClass"
        :style="maskStyleComputed"
        @click.self="handleClick"
      >
        <div v-if="close" class="s-mask__close" @click="handleClose">
          <slot name="close">
            <div class="s-mask__close__icon" :class="closeClass" :style="closeStyle">
              <s-icon :icon-props="{ icon: X }" />
            </div>
          </slot>
        </div>
        <slot></slot>
      </div>
    </template>
    <template v-else>
      <div
        class="s-mask"
        v-show="value"
        :class="maskClass"
        :style="maskStyleComputed"
        @click.self="handleClick"
      >
        <div v-if="close" class="s-mask__close" @click="handleClose">
          <slot name="close">
            <div class="s-mask__close__icon" :class="closeClass" :style="closeStyle">
              <s-icon :icon-props="{ icon: X }" />
            </div>
          </slot>
        </div>
        <slot></slot>
      </div>
    </template>
  </Teleport>
</template>

<style lang="scss">
  @use './style' as *;
</style>
